//
//  SimpleCollectionViewCell.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 16/12/18.
//  Copyright © 2016年 com.xtion.crm. All rights reserved.
//

#import "SimpleCollectionViewCell.h"

#define Item_Size_80 80
#define Item_Size_100 100

@interface SimpleCollectionViewCell()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
{
    UICollectionView *_collectionView;
    
    XMSQueueDictionary *_MenuIndex;
    
    UILabel *_titleLabel;
    UIView *_BackgroundView;
}
@end

@implementation SimpleCollectionViewCell

-(instancetype)init
{
    return [self initWithFrame:CGRectZero];
}

-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    self.backgroundColor = [UIColor colorWithHex:mcrmSAASUISkinColorTextStylef1f4f7Color];
    
    [self initVariable];
    
    _BackgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 40)];
    _BackgroundView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:_BackgroundView];

    _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, 200,30)];
    _titleLabel.font = [UIFont systemFontOfSize:12];
    _titleLabel.textColor = [UIColor colorWithHex:mcrmSAASUIShinColorTextStyle2196F3Color];
    
    [_BackgroundView addSubview:_titleLabel];
    
    [self collectionView];

    return self;
}

- (void)initVariable
{ 
    _MenuIndex = [XMSQueueDictionary new];
    _qdData = [NSArray new];
    
    [self addMainThreadObserverWithDictionarySelector:@{XLGHeadImageDownloadQueueHeadImageDownloadResultNotification:@"observerHeadImageDownloadQueueHeadImageDownloadResultNotification:"}];
}

- (void)setQdData:(NSArray *)qdData
{
    _qdData = qdData;
    
    NSInteger index = 0;
    for (MenuInfo *info in qdData)
    {
        [_MenuIndex setValue:info forKey:@(index)];
        
        index ++;
    }
    
    [self.contentView addSubview:self.collectionView];
}

- (void)setTitle:(NSString *)title
{
    _titleLabel.text = title;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    if(_titleLabel.hidden == YES)
    {
        _titleLabel.height = 0;
        
        _collectionView.top = self.contentView.top;
        _collectionView.height = self.contentView.size.height;
    }
    else
    {
        _collectionView.top = _titleLabel.bottom;
        _collectionView.height = self.contentView.size.height - _titleLabel.height;
    }
    
    _BackgroundView.width = self.contentView.width;
    _titleLabel.centerY = _BackgroundView.centerY;
}

- (void)setHiddenTitle:(BOOL)hiddenTitle
{
    _titleLabel.hidden = hiddenTitle;
}

#pragma mark - 创建collectionView并设置代理
- (UICollectionView *)collectionView
{
    if (_collectionView == nil) {
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumLineSpacing = 1;
        flowLayout.minimumInteritemSpacing = 1;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.contentView.size.width, 0) collectionViewLayout:flowLayout];
        
        //注册cell
        [_collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
        
        //设置代理
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        //禁止滚动
        _collectionView.scrollEnabled = false;
        //背景颜色
        _collectionView.backgroundColor = [UIColor colorWithHex:mcrmSAASUISkinColorTextStylef1f4f7Color];
        //自适应大小
        _collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        
        _collectionView.alwaysBounceVertical = YES;
    }
    return _collectionView;
}

#pragma mark - UICollectionView delegate dataSource
#pragma mark 定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [_MenuIndex count];
}

#pragma mark 定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

#pragma mark 每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify = @"cell";
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    [cell sizeToFit];
    
    MenuInfo *info = [_MenuIndex getValueForIndex:indexPath.item];
    
    if(info != nil)
    {
        cell.szTag = info.menuId;
        cell.title = info.name;
        
        UIImage *headImage = nil;
        if(info.icon.length >0)
        {
            if([info.icon rangeOfString:ServiceDefaultHeadImageTag].location == NSNotFound)
            {
                XLGHeadImageCache *cache = [XLGHeadImageDownloadQueue checkOrStartDownloadHeadImageWhenAddHeadImageURL:info.icon forKey:XLGHeadImageDownloadQueueSysIcon];
                if(cache != nil)
                    headImage = cache;
                else
                    headImage = [UIImage imageNamed:@"img_defaultmenu.png"];
            }
            else
            {
                NSString *h = [info.icon substringFromIndex:[info.icon rangeOfString:ServiceDefaultHeadImageTag].length];
                headImage = [UIImage imageNamed:h];
            }
        }
        else
            headImage = [UIImage imageNamed:@"img_defaultmenu.png"];
        
        headImage = [UIImage resizeImage:headImage withNewSize:CGSizeMake(100, 100)];
        
        cell.bgImg = headImage;
    }
    return cell;
}


#pragma mark --
#pragma mark -- refresh headImage
-(void)observerHeadImageDownloadQueueHeadImageDownloadResultNotification:(NSNotification*)noti
{
    NSString *path =[noti.userInfo objectForKey:XLGHeadImageDownloadQueueHeadImageDownloadResultPathKey];
    NSString *URL =[noti.userInfo objectForKey:XLGHeadImageDownloadQueueHeadImageDownloadResultURLKey];
    
    for (MenuInfo *info in _qdData)
    {
        if([info.icon isEqualToString:URL])
        {
            XLGHeadImageCache *cache = [XLGHeadImageDownloadQueue setCacheWithHeadImageURL:URL andHeadImagePath:path forKey:XLGHeadImageDownloadQueueSysIcon];
            
            UIImage *headImage = (UIImage*)cache;
            headImage = [UIImage resizeImage:headImage withNewSize:CGSizeMake(100, 100)];
            
            for(CollectionViewCell *cell in self.collectionView.visibleCells)
            {
                if([cell.szTag isEqualToString:info.menuId])
                {
                    cell.bgImg = headImage;
                }
            }
        }
    }
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if([_delegate respondsToSelector:@selector(simpleCollectionViewCell:clickedButton:info:)])
    {
        MenuInfo *info = [_MenuIndex getValueForIndex:indexPath.item];
        [_delegate simpleCollectionViewCell:self clickedButton:nil info:info];
    }
}

#pragma --
#pragma -- UICollectionViewDelegateFlowLayout
//配置每个item的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
     CGSize size = CGSizeMake(([UIDevice screenWidth] - (_uiEdgeInsets.left + _uiEdgeInsets.right)*_itemCount) / _itemCount, [UIDevice screenWidth] / _itemCount);
    
    return size;
}

//配置item的边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return _uiEdgeInsets;//上左下右
}

+(CGFloat)caleHeight:(NSInteger)dataCount itemCount:(NSInteger)itemCount itemHeight:(NSInteger)itemHeight hiddenTitle:(BOOL)hiddenTitle
{
    CGFloat itemSizeHeight = [UIDevice screenWidth] / itemCount;
    NSInteger mode = dataCount % itemCount;
    NSInteger count = dataCount / itemCount;
    if(mode >0)
        count ++;
    
    CGFloat height = (count * itemSizeHeight) + (count * itemHeight * 2);
    
    if(hiddenTitle == NO)
    {
        height += 40;
    }
    return height;
}

@end
